<?php
function game_go(&$arrReturn)
{ 
    global $db;
    $speNo = $_GET['no'];
    $nowTime = strtotime(date('Y-m-d H:i:s',time()));
    $BeginTime = strtotime(date('Y-m-d',time()) . " 07:00:00");
	$EndTime = strtotime(date('Y-m-d',time()) . " 05:05:00"); 
    
    
    if($nowTime >= $EndTime && $nowTime < $BeginTime)
    {
    	//取下期时间
    	$sql = "SELECT id,kgtime FROM gamehg28 WHERE kj = 0 AND kgtime > NOW() order by id limit 1";
        $query = $db->query($sql);
        if($rs = $db->fetch_array( $query ))
        {
             $arrRet['nextid'] = $rs['id'];
             $arrRet['nexttime'] = $rs['kgtime'];
        }
        else
        {
			 $sql = "select DATE_ADD(NOW(),INTERVAL 60 SECOND) nowtime";
        	 $query = $db->query($sql);
        	 $rs = $db->fetch_array( $query );
			 $arrRet['nextid'] ='0';
             $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
        }
    	$arrReturn['msg'] = 'not in open game time(hg)';
    	return;
	}
    
    $No = intval($speNo);
    $arrCatchNo = array();
    if($speNo == 0) //取最新开奖
    {
		$sql = "SELECT id FROM gamehg28 WHERE kj = 0 AND kgtime < NOW() AND kgtime > DATE_ADD(NOW(),INTERVAL -60 MINUTE)
		        and id not in(select gameno from game_result where gametype = 'gamehg')
				ORDER BY id DESC";
    	$query = $db->query($sql);
    	$i = 0;
    	while($rs = $db->fetch_array( $query ))
    	{
    		$arrCatchNo[$i] = $rs["id"];
    		$i++;
		} 
    }
    else
    {
		$sql = "SELECT id FROM gamehg28 WHERE kj = 0 and id = '{$No}' ";
    	$query = $db->query($sql);
    	if($rs = $db->fetch_array( $query ))
    	{
    		$arrCatchNo[0] = $rs["id"];
		}
    	else
    	{ 
    		$arrReturn['code'] = "ok";
    		$arrReturn['msg'] = "{$No} had opened(hg)";
    		$arrReturn['log'] .= LogFormat("{$No} had opened(hg)");
    		return;
		}
    }
    if(count($arrCatchNo) == 0)
    {
    	 CatchResult($arrCatchNo);
		 $arrReturn['code'] = "ok";
		 $arrReturn['no'] = "0";
    	 $arrReturn['msg'] = "no record to catch(can)";
    	 $arrReturn['log'] .= LogFormat("no record to catch(hg)");
    	 return;
    }
    $ret = CatchResult($arrCatchNo);
    if ( $ret != "")
    {
		$arrReturn['code'] = "ok";
		$arrRet['nextid'] = "catch_ok";
		$arrReturn['msg'] = "catch_ok";
		$arrReturn['no'] = $ret; 
		$strlog = "catched hg: {$ret},result had been saved(hg)";
    	$arrReturn['log'] .= LogFormat($strlog);
    }
    else //取不到结果
	{
		$ret = implode(',',$arrCatchNo);
		$arrReturn['code'] = 'ok';
		$arrReturn['no'] = $ret;
		$arrReturn['msg'] = "can not catch {$ret} result(hg)";
		$arrReturn['log'] = LogFormat("can not catch {$ret} result!(hg)");
	} 
}

function CatchResult($arr)
{
	global $db;
	$ret = "";
	$kjcontent=hk_hg();
	if($kjcontent){
		foreach ($arr as $key=>$value){
			foreach ($kjcontent as $k=>$v) {
				if($value!=$v['l_t'])continue;
				$v['c_r']=str_replace(',','|' ,$v['c_r'] );
				$sql = "call web_savecatch_result('gamehg',{$value},'{$v[c_r]}')";
				$arrT = $db->Mysqli_Multi_Query($sql);
				$ret .= $v;
			}
		}
		return $ret;
	}
	$kjcontent = GetGameResult(); 
	$kjcontent = iconv("EUC-KR","UTF-8//IGNORE",$kjcontent);
	if(strlen($kjcontent) > 0)
	{
		foreach($arr as $key => $v) 
		{
			$rewardstr = "";
			$kjnum = getbodyc($kjcontent,"<td>{$v}</td>","</td>");
			$kjnum = trim($kjnum);
			$arrNum = explode("<td>",$kjnum);
			if(count($arrNum) > 0)
			{
				$rewardstr = str_replace(",","|",$arrNum[1]);
				if(strlen($rewardstr) > 0)
				{
					$sql = "call web_savecatch_result('gamehg',{$v},'{$rewardstr}')";
					$arrT = $db->Mysqli_Multi_Query($sql);
					$ret .= $v . " ";
				}
			}
		}
	}
	return $ret;
}

function hk_hg(){
	$url="http://203.88.161.240:899/jlotto/get_jlotto_data.php?key=whoami";
	$html=file_get_contents($url);
	if($html){
		$html=json_decode($html,true);
		return $html;
	}
	return false;

}

function GetGameResult()
{
	$kjContent = GetGameResult_jlotto();
    return $kjContent;
}


function GetGameResult_jlotto()
{
	$kjcontent = fsockurl("http://www.jlotto.kr/keno.aspx?method=kenoWinNoList");
	return $kjcontent;
}
error_reporting( 0 );
set_time_limit(120);
include_once( "inc/conn.php" );
include_once( "inc/function.php" );


if ( $_GET['key'] == "catch_result_hanguo" )
{   
    $arrRet = array('code'=>'ok', //
    				'no' =>'',
                    'msg'=>'', //错误信息 -1:不在开奖时间内，0：开奖成功，1：该期已开过奖，2：取中奖赔率错误，99：系统错误
                    'log'=>'',
                    'nextid'=>'', //下一盘id
                    'nexttime'=>'' //下一篇开奖时间
        );
    game_go($arrRet);
    if ($arrRet['nextid'] == 'catch_ok')
    {
    	$RandSecond = rand(30,40);
        $sql = "SELECT id,DATE_ADD(kgtime,interval {$RandSecond} second) kgtime FROM gamehg28 WHERE kj = 0 AND kgtime > NOW() limit 1";
        $query = $db->query($sql);
        if($rs = $db->fetch_array( $query ))
        {
             $arrRet['nextid'] = $rs['id'];
             $arrRet['nexttime'] = $rs['kgtime'];
        }
        else
        {
        	 $arrRet['nextid'] ='0';
             $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
        }
    }
    else
    {
		$RandSecond = rand(10,20);
		$sql = "select date_add(NOW(),INTERVAL {$RandSecond} SECOND) nowtime,id from gamehg28 where kgtime > now() and kj = 0 order by id limit 1";
		$query = $db->query($sql);
		if($rs = $db->fetch_array( $query ))
		{
			$arrRet['nextid'] = $rs['id'];
			$arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime($rs["nowtime"]));
		}
		else
		{
			$arrRet['nextid'] ='0';
            $arrRet['nexttime'] = date('Y-m-d H:i:s',strtotime("+{$RandSecond} second"));
		}
    }
    //返回
    echo  json_encode($arrRet);
}
$db->close( );
